<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title"
                style="text-align: center; display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="font-size: 18px; font-weight: bold; color: #333;">
                    {{ sales_Return.sale_Order_Name }}&nbsp;{{ sales_Return.sale_Order_Code }}
                </div>
                <div style=" height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handleAudit">审核</el-button>
                </div>
            </div>

            <hr style="border: 0; height: 1px; background: #e0e0e0; margin: 10px 0 20px;">

            <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                <tbody>
                    <!-- 第一行 -->
                    <tr>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            客户名称</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            sales_Return.customer_Name }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            联系人</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            sales_Return.contacts_Name }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            联系电话</td>
                        <td style="padding: 12px 15px; width: 15%;">{{
                            sales_Return.contacts_Phone }}</td>
                    </tr>

                    <!-- 第二行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库仓库</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.warehouse_name }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库库位</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.zone_name }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库员</td>
                        <td style="padding: 12px 15px;">{{ userValue(sales_Return.sale_Return_Rep_Id)
                        }}</td>
                    </tr>

                    <!-- 第三行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            入库员部门</td>
                        <td style="padding: 12px 15px;">{{
                            deptValue(sales_Return.sale_Return_Dept_Id) }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            订单状态</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.status
                        }}</td>
                        <!-- <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户状态</td>
                        <td style="padding: 12px 15px;">{{
                            sales_order.sale_order_name }}</td> -->
                    </tr>

                    <!-- 第六行 - 创建信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建人</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.create_By }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建时间</td>
                        <td style="padding: 12px 15px;" colspan="3">{{ sales_Return.create_Time.replace('T', ' ') ||
                            '无'
                            }}</td>
                    </tr>

                    <!-- 第七行 - 修改信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改人</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.update_By === 'null' ? '暂无' :
                            sales_Return.update_By }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ sales_Return.update_Time === 'null' ? '暂无' : sales_Return.update_Time.replace('T', ' ') }}
                        </td>
                    </tr>

                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核人</td>
                        <td style="padding: 12px 15px;">{{ sales_Return.sale_Return_Audit_By === 'null' ? "暂无" :
                            sales_Return.sale_Return_Audit_By }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            审核时间</td>
                        <td style="padding: 12px 15px;" colspan="3">
                            {{ sales_Return.sale_Return_Audit_Time === 'null' ? "暂无" :
                                sales_Return.sale_Return_Audit_Time.replace('T', ' ')}}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">销售产品明细</h2>
            <!-- <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="detailstAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div> -->
            <el-table :data="selectedDetailsData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable">
                <el-table-column prop="pro_Name" label="产品名称" width="130" />
                <el-table-column prop="pro_Code" label="产品编号" width="160" />
                <el-table-column prop="pro_Brand" label="品牌" width="100" />
                <el-table-column prop="pro_Model" label="规格型号" />
                <el-table-column prop="measure_Id" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.measure_Id) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_Sale_Qty" label="销售数量" />
                <el-table-column prop="pro_outbound_qty" label="已出库" />
                <el-table-column prop="unshipped_qty" label="未出库" />
                <el-table-column prop="pro_Return_Qty" label="本次退货数量" width="120px" />
                <el-table-column prop="pro_Sale_Price" label="销售单价" />
                <el-table-column prop="pro_Return_Price" label="退货金额" />
                <!-- <el-table-column prop="address" label="出库库位">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_code" placeholder="选择库位" size="small"
                            @change="(val) => handleLocationChange(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column> -->
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">退货总数量：{{ sale_return_total_qty }} &nbsp;&nbsp;&nbsp;
                    退货总金额：{{
                        pro_return_total_price }} &nbsp;&nbsp;&nbsp;
                    订单状态：{{ return_status }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, inject, watch, toRaw, markRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage, handleEdit, ElMessageBox, ElLoading } from 'element-plus';
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import dayjs from 'dayjs'
export default {
    setup() {
        const store = useStore()
        const code = store.state.SalesReturnCode
        const sales_Return = reactive({
            sale_Return_Id: "",//销售退货id
            sale_Return_Code: "",//销售出库编号
            warehouse_code: "",//出库仓库编号
            warehouse_name: "",//出库仓库名称
            zone_code: "",//出库库区编号
            zone_name: "",//出库库区名称
            location_code: "",//出库库位编号
            location_name: "",//出库库位编号
            customer_Name: "",//客户名称
            customer_Code: "",//客户编号
            contacts_Name: "",//联系人名称
            contacts_Phone: "",//联系人电话/联系方式
            sale_Return_Store_Time: "",//入库时间
            sale_Return_Rep_Id: "",//入库员
            sale_Return_Dept_Id: "",//入库员所属部门
            sale_Order_Name: "",//销售订单名称
            sale_Order_Code: "",//销售订单编号
            sale_Order_Rep_Id: "",//销售负责人
            sale_Order_Dept_Id: "",//负责人部门
            sale_Return_Status: "",//入库状态
            sale_Return_Reason: "",//退货原因
            create_By: "",//创建人
            create_Time: "",//创建时间
            update_By: "",//修改人
            update_Time: "",//修改时间
            sale_Return_Audit_By: "",//审核人
            sale_Return_Audit_Time: "",//审核时间
            sale_Return_Audit_Status: "",//审核状态
            status: "",//记录订单状态
        })
        const deptOptions = ref([])
        const userOptions = ref([])
        const measureOptios = ref([])
        const sale_return_total_qty = ref(0)//记录本次退货总数量
        const pro_return_total_price = ref(0)//记录本次退货总金额
        const return_status = ref('')//记录本次出库状态
        const selectedDetailsData = ref([])
        const detailsData = ref([])
        const centerDialogVisible = ref(false)
        const auditStatus = ref('1')
        const auditOpinion = ref('')
        const router = useRouter()

        onMounted(async () => {
            getUser()
            getDept()
            getMeasure()
            await fillSalesRturn()
            await fillReturnOutboundDetails();
        })

        watch(selectedDetailsData, (newVal) => {
            //每次计算时清空累加
            sale_return_total_qty.value = 0
            pro_return_total_price.value = 0
            return_status.value = ''
            let pro_Return_Qty = 0//记录待出库总数量
            let pro_sale_qty = 0//记录出库总数量
            newVal.forEach(row => {

                if (isNaN(Number(row.pro_Return_Qty))) {
                    ElMessage.warning('退货数量必须是数字');
                    row.pro_Return_Qty = 0;
                }

                if (row.pro_Return_Qty > row.pro_Sale_Qty) {
                    ElMessage.warning('退货数量不能大于销售库数量');
                    row.pro_Return_Qty = row.pro_Sale_Qty
                }

                sale_return_total_qty.value += Number(row.pro_Return_Qty)
                pro_return_total_price.value += Number(row.pro_Return_Price)
                pro_Return_Qty += Number(row.pro_Return_Qty)
                pro_sale_qty += Number(row.pro_Sale_Qty)
                row.pro_Return_Price = (Number(row.pro_Return_Qty || 0) * Number(row.pro_Sale_Price || 0)).toFixed(2);
            });
            return_status.value = pro_Return_Qty == pro_sale_qty ? '全部入库' : '部分入库'
            sales_Return.sale_Return_Status = pro_Return_Qty == pro_sale_qty ? 2 : 1
        }, { deep: true });

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getDept() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            const parentDept = deptOptions.value.find((dept) => dept.dept_id == row)
            return parentDept ? parentDept.dept_name : "无"
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOptions.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }
        //查询计量单位
        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称
        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        //查询销售退货信息
        async function fillSalesRturn() {
            try {
                const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_ReturnByCode", {
                    params: { code: code }
                });

                // 同步赋值
                for (const key in sales_Return) {
                    // 排除数字类型字段（如 user_id、dept_id）
                    if (key === 'sale_Order_Rep_id' || key === 'sale_Order_Dept_id' || key === 'sale_Return_Rep_Id' || key === 'sale_Return_Dept_Id') {
                        sales_Return[key] = Number(result.data[key]); // 保留数字类型
                    } else if (key === 'sale_Return_Store_Time') {
                        sales_Return[key] = new Date(result.data[key]).toISOString();
                    } else {
                        sales_Return[key] = String(result.data[key]); // 其他字段转字符串
                    }
                }
                sales_Return.warehouse_name = result.data.warehouse_Name
                sales_Return.zone_name = result.data.zone_Name
                if (sales_Return.sale_Return_Audit_Status === '0') {
                    sales_Return.status = '待审核';
                } else if (sales_Return.sale_Return_Audit_Status === '1') {
                    // 审核通过，显示出库状态
                    switch (sales_Return.sale_Return_Status) {
                        case '0':
                            sales_Return.status = '待出库';
                            break;
                        case '1':
                            sales_Return.status = '部分出库';
                            break;
                        case '2':
                            sales_Return.status = '全部出库';
                            break;
                        default:
                            sales_Return.status = '未知出库状态';
                    }
                } else if (sales_Return.sale_Return_Audit_Status === '2') {
                    sales_Return.status = '审核驳回';
                } else {
                    sales_Return.status = '未知状态';
                }
            } catch (err) {
                console.error("加载销售退货数据失败:", err);
                ElMessage.error("销售退货数据加载失败");
            }
        }

        //查询销售退货明细
        async function fillReturnOutboundDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_Return_DetailsByCode", {
                    params: { code: code }
                });
                await fillSalesDetails()
                selectedDetailsData.value = result.data.map(returnDetail => {
                    // 在 detailsData 中查找对应的销售订单明细
                    const saleDetail = detailsData.value.find(
                        detail => detail.pro_code === returnDetail.pro_Code
                    );
                    return {
                        // pro_Return_Price: Number(returnDetail.pro_Return_Price),
                        ...returnDetail,
                        pro_Sale_Price: saleDetail?.pro_sale_price || 0, // 如果找不到，默认设为 0
                        unshipped_qty: saleDetail?.unshipped_qty || 0,
                        pro_outbound_qty: saleDetail?.pro_outbound_qty || 0,
                    };
                });
                // console.info(result.data)
                // selectedDetailsData.value = result.data
                // console.info(selectedDetailsData.value)
            } catch (err) {
                console.error("加载销售退货明细失败:", err);
                ElMessage.error("销售退货明细加载失败，请检查网络或API");
            }
        }
        async function fillSalesDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Order_DetailsByCode", {
                    params: {
                        code: sales_Return.sale_Order_Code,
                    },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });

                // 处理数据：添加默认值保护，移除多余的 async
                detailsData.value = result.data.map((item) => ({
                    ...item,
                    unshipped_qty: (Number(item.pro_sale_qty || 0) - Number(item.pro_outbound_qty || 0)) - Number(item.pro_return_qty || 0),
                    // pro_Return_Qty: item.pro_Return_Qty || 0,
                    // pro_Return_Price: (Number(item.pro_Return_Qty || 0) * Number(item.pro_sale_price || 0)).toFixed(2)
                }));
            } catch (err) {
                console.error("请求失败:", err);
            }
        }

        function handleEdit() {
            if (sales_Return.sale_Return_Audit_Status != '0') {
                ElMessage.warning('审核通过后不允许再次编辑！')
                return
            }
            store.commit("SalesReturnCode", sales_Return.sale_Return_Code)
            router.push("/main/Sinv/SalesReturnUpdate")
        }


        //审核按钮
        function handleAudit() {
            if (sales_Return.sale_Return_Audit_Status != '0') {
                ElMessage.warning('已审核过的订单不允许再次审核！')
                return
            }
            centerDialogVisible.value = true
            sale_return_id.value = sales_Return.sale_Return_Id
        }

        //确定审核按钮
        function updateAudit() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在修改中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            axios.put("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_ReturnAuditUpdate", {
                sale_Return_Id: sale_return_id.value,
                sale_Return_Audit_By: localStorage.getItem('userLName'),
                sale_Return_Audit_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                sale_Return_Audit_Opinion: auditOpinion.value,
                sale_Return_Audit_Status: auditStatus.value
            }, {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    if (auditStatus.value == '1') {
                        ElMessage.success('审核通过')
                    } else if (auditStatus.value == '2') {
                        ElMessage.warning('审核已被驳回！')
                    }
                    handleClose()
                } else {
                    ElMessage({
                        type: 'danger',
                        message: '销售退货订单审核失败！'
                    });
                }
            }).catch((err) => {
                console.info(err)
            }).finally(() => {
                loadingInstance.close();
            })
        }

        //关闭审核按钮
        function close() {
            auditOpinion.value = ""
            auditStatus.value = '1'
            centerDialogVisible.value = false
        }

        //点击删除
        function handleDelete() {
            if (sales_Return.sale_Return_Audit_Status != '0') {
                ElMessage.warning('审核通过后不允许进行删除！')
                return
            }
            ElMessageBox.confirm(
                '此操作将删除'+sales_Return.sale_Return_Code+'退货订单，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    const loadingInstance = ElLoading.service({
                        lock: true,
                        text: '正在删除中...',
                        background: 'rgba(0, 0, 0, 0.7)',
                    });
                    axios.put("http://localhost:5181/api/Sinv_Sale_Return/Sinv_Sale_ReturnDel", {
                        sale_Return_Id: sales_Return.sale_Return_Id,
                        del_flag: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.success('销售退货删除成功！')
                            fill();
                            count();
                        } else {
                            ElMessage({
                                type: 'danger',
                                message: '销售退货订单删除失败！'
                            });
                        }
                    }).catch((err) => {
                        console.info(err)
                    }).finally(() => {
                        loadingInstance.close();
                    })
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function handleClose() {
            const targetPath = "/main/Sinv/SalesReturn";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "销售退货",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        return {
            sales_Return, userValue, deptValue, sale_return_total_qty, pro_return_total_price, return_status, selectedDetailsData, measureValue,
            measureOptios, handleEdit, handleAudit, updateAudit, close, auditOpinion, auditStatus, centerDialogVisible, handleClose, handleDelete
        }
    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}
</style>